<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Service\DataReturnService as DRS;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\TicketController as T;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use App\Common\Base;
use App\Service\DeliveryService;

/**
 * 收货地址逻辑
 */
class DeliveryController extends Controller
{

    /**
     * 2018-06-28
     * czw
     * 添加收货地址
     */
    public function add(Request $R)
    {
        $data = $R->post();
        $rule = [
            'token' => 'required',
            'name' => 'required',
            'phone' => 'required',
            'province' => 'required',
            'city' => 'required',
            'district' => 'required',
            'address' => 'required',
        ];
        $msg = [
            'token.required' => '缺失token',
            'name.required' => '收货人必填',
            'phone.required' => '手机号必填',
            'province.required' => '省份必选',
//            'province.numeric' => '省份必须传数字',
            'city.required' => '城市必选',
//            'city.numeric' => '城市必须传数字',
            'district.required' => '区必选',
//            'district.numeric' => '区必须传数字',
            'address.required' => '详细地址不能为空'
        ];
        $validator = Validator::make($data,$rule,$msg);
        if ($validator->fails()) {
            return DRS::returnError(20281,$validator->errors()->first());
        }

        $userInfo = Base::getUserByToken($data['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        
        $check_mobile = Base::check_mobile($data['phone']);
        if($check_mobile){
            return DRS::returnError($check_mobile['code'], $check_mobile['msg']);
        }

        $delivery_insert = [
            'user_id' => $user['id'],
//            'business_id' => $user['business_id'],
            'province' => $data['province'],
            'city' => $data['city'],
            'district' => $data['district'],
            'address' => $data['address'],
            'phone' => $data['phone'],
            'name' => $data['name'],
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
        ];

        if(array_key_exists('is_default', $data)){
            if($data['is_default'] == 1){
                DB::table('delivery')->where(['user_id' =>$user['id']])->update(['is_default' => 0]);
                $delivery_insert['is_default']= 1;
            }
        }
        
        $delivery_id = DB::table('delivery')->insertGetId($delivery_insert);
        if($delivery_id){
            return DRS::returnOk(['id'=>$delivery_id], '新增收货地址成功');
        }else{
            return DRS::returnError(20282, '新增收货地址失败', []);
        }
    }

    /**
     * 2018-06-28
     * czw
     * @param id int 地址id
     * 地址详情
     */
    public function info(Request $R) 
    {
        $data['token']  = $R->get('token');
        $data['id']     = $R->get('id');

        $validator = Validator::make($data,
                [
                    'token' => 'required|string',
                    'id'    => 'required',
                ],
                ['id.required'  => 'id不能为空']
            );
        if ($validator->fails()) {
            return DRS::returnError(20003,$validator->errors()->first());
        }
        
        $userInfo = Base::getUserByToken($data['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        
        $delivery_info = (array) DB::table('delivery')->where(['id'=>$data['id'],'user_id'=>$user['id'],'state'=>0])->first();
        if($delivery_info == null){
            return DRS::returnError(20003,'不存在该收货地址');
        }
        $delivery_info['address_info'] = $delivery_info['province'].$delivery_info['city'].$delivery_info['district'].$delivery_info['address'];

        if($delivery_info){
            return DRS::returnOk($delivery_info,'获取地址详情成功');
        }else{
            return DRS::returnError(22810,'获取地址详情失败');
        }
    }
    
    /**
     * 2018-06-28
     * czw
     * 收货地址列表
     */
    public function list(Request $R) 
    {
        $token = $R->get('token');
        $validator = Validator::make(['token' => $token],
                [
                    'token' => 'required|string', 
                ],
                [
                    'token.required' => 'token不能为空',
                ]);
        if ($validator->fails()) {
            return DRS::returnError(20003,$validator->errors()->first());
        }
        $userInfo = Base::getUserByToken($token);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        $where = [
            'delivery.user_id' => $user['id'],
            'delivery.state' => 0,
        ];
        $delivery_list_query = DB::table('delivery')->where($where)->orderBy('update_time','desc')->get()->toarray();
        $delivery_list = array_map('get_object_vars', $delivery_list_query);

        foreach ($delivery_list as $dkey => $dvalue) {
                $delivery_list[$dkey]['address_info'] = $dvalue['province'].$dvalue['city'].$dvalue['district'].$dvalue['address'];
            }
        if($delivery_list){
            return DRS::returnOk($delivery_list,'获取收货地址列表成功');
        }else{
            return DRS::returnOk($delivery_list,'还没有添加收货地址哦');
        }

    }
    
    /**
     * 2018-06-28
     * czw
     * @param id int 地址id
     * 获取默认地址
     */
    public function default(Request $R) 
    {
        $token = $R->get('token');
        $validator = Validator::make(['token' => $token],
                [
                    'token'     => 'required|string',
                ],
                [
                    'token.required'    => 'token不能为空',
                ]
            );
        if ($validator->fails()) {
            return DRS::returnError(20003,$validator->errors()->first());
        }

        $userInfo = Base::getUserByToken($token);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        
        $where = [
            ['user_id','=',$user['id']],
            ['state','=',0], // 没有删除
            ['is_default','=',1],
        ];
        
        $delivery_info = (array)DB::table('delivery')->where($where)->first();

        if($delivery_info != null && !empty($delivery_info)){
            $delivery_info['address_info'] = $delivery_info['province'].$delivery_info['city'].$delivery_info['district'].$delivery_info['address'];
        }
        $delivery_info = empty($delivery_info) ? null :  $delivery_info;
        return DRS::returnOk($delivery_info);
    }

    /**
     * 2018-06-28
     * czw
     * @param id int 编辑的地址id
     * 修改收货地址
     */
    public function update(Request $R) 
    {
        $data = $R->post();
        $rule = [
            'token'         => 'required|string',
            'id'            => 'required',
            'name'          => 'required',
            'phone'         => 'required',
            'province'      => 'required',
            'city'          => 'required',
            'district'      => 'required',
            'address'       => 'required',
            'is_default'    => 'required'
        ];
        $msg = [
            'token.required'    => '不能缺失token',
            'id.required'       => '编辑的地址id必传',
            'name.required'     => '收货人必填',
            'phone.required'    => '手机号必填',
            'province.required' => '省份必选',
            'city.required'     => '城市必选',
            'district.required' => '区必选',
            'address.required'  => '详细地址不能为空',
            'is_default'        => '是否默认',
        ];
        $validator = Validator::make($data,$rule,$msg); 
        if ($validator->fails()) {
            return DRS::returnError(20281,$validator->errors()->first());
        }

        $userInfo = Base::getUserByToken($data['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user = $userInfo['data'];
        $check_mobile = Base::check_mobile($data['phone']);
        if($check_mobile){
            return DRS::returnError($check_mobile['code'], $check_mobile['msg']);
        }

        $where = [
            'id'        => $data['id'],
            'user_id'   => $user['id'],
            'state'     => 0
        ];
        $delivery_update = [
            'province'      => $data['province'],
            'city'          => $data['city'],
            'district'      => $data['district'],
            'address'       => $data['address'],
            'phone'         => $data['phone'],
            'name'          => $data['name'],
            'is_default'    => $data['is_default'],
            'update_time'   => date('Y-m-d H:i:s'),
        ];
        if(array_key_exists('is_default', $data)){
            if($data['is_default'] == 1){
                DB::table('delivery')->where(['user_id'=>$user['id']])->update(['is_default'=>0]);  
            }
        }
        
        $address = DB::table('delivery')->where($where)->first();
        if($address == null){
            return DRS::returnError(20284, '该收货地址不存在');
        }
        $delivery_id = DB::table('delivery')->where($where)->update($delivery_update);

        $delivery_info = (array)DB::table('delivery')->where(['id' => $data['id']])->first();

        $delivery_info['address_info'] = $delivery_info['province'].$delivery_info['city'].$delivery_info['district'].$delivery_info['address'];
        if($delivery_info){
            return DRS::returnOk($delivery_info, '修改收货地址成功');
        }else{
            return DRS::returnError(20284, '修改收货地址失败', []);
        }
    }
    
    /**
     * 2018-06-28
     * czw
     * @param id array
     * 删除收货地址
     */
    public function remove(Request $R) 
    {
        $data['token']  = $R->get('token'); 
        $data['id']     = $R->get('id'); 

        $validator = Validator::make($data,
                [
                    'token' => 'required|string',
                    'id'    => 'required|array'
                ],
                [
                    'token.required'    => 'token不能为空',
                    'id.required'       => 'id不能为空',
                    'id.array'          => 'id应为数组'
                ]
            );
        if ($validator->fails()) {
            return DRS::returnError(20003,$validator->errors()->first());
        }

        $userInfo = Base::getUserByToken($data['token']);
        if($userInfo['code'] != '666'){
            return $userInfo;
        }
        $user   = $userInfo['data'];
        
        if(DeliveryService::check_delivery($data['id'],$user['id']) == FALSE){
           return DRS::returnError(20280,'没有该地址');
        }
        $where = [
            ['user_id','=',$user['id']],
            ['state','=',0], // 没有删除
        ];
        $delivery_up = DB::table('delivery')->where($where)->whereIn('id',$data['id'])->update(['state'=>1]);
        if($delivery_up){
            return DRS::returnOk(true,'删除收货地址成功');
        }else{
            return DRS::returnError(20287,'删除收货地址失败');
        }
        
    }
    
}